package com.hsgene.pay.service.support;

import com.hsgene.common.util.qrcode.PayQrCodeUtils;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.pay.exception.PayErrorCode;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * 支付二维码生成支持类
 * PS：为了复用代码，从原OrderPayController的getPayCode方法提取到这个单独的类中
 *
 * @author wangbing
 * @version 1.0
 * @date 2019/1/29 10:06
 * Copyright: Copyright (c) 2019
 */
public class QrCodeSupport {

    private static final Logger LOGGER = LoggerFactory.getLogger(QrCodeSupport.class);

    public static ApiResult<String> getPayCode(HttpServletResponse response, Map<String, Object> result)
            throws IOException {
        response.setContentType("image/jpeg;charset=UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        String url = (String) result.get("payUrl");
        if (StringUtils.isEmpty(url)) {
            LOGGER.error("pay code url is null...");
            return ApiResult.fail(PayErrorCode.PAY_CODE_IS_NOT_EXISTS);
        }
        //二维码
        BufferedImage bufferedImage = PayQrCodeUtils.qrCodeEncode(url);
        if (bufferedImage == null) {
            LOGGER.error("pay code generate is error...");
            return ApiResult.fail(PayErrorCode.PAY_CODE_GENERATE_ERROR);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String imageCode = encoder.encode(os.toByteArray());
        LOGGER.info("pc pay code is success...");
        return ApiResult.succ(imageCode);
    }
}
